<?php
namespace App\Core\Entity\Session;

class LocationEntity extends Factory
{

    /**
     * 定位地址内部 key（手动选择地址）
     */
    const KEY_DISTRICT = 'district';

    public function __construct(array $data = [])
    {
        if (! count($data) && session()->has(self::SESSION_KEY_LOCATION)) {
            $data = session()->get(self::SESSION_KEY_LOCATION);
        }
        parent::__construct($data);
    }

    /**
     * 获取 district 地址
     *
     * @return array
     */
    public function getDistrict()
    {
        return $this->offsetExists(self::KEY_DISTRICT) ? $this->offsetGet(self::KEY_DISTRICT) : [];
    }

    /**
     * 保存 district 地址
     *
     * @param array $district            
     * @return $this
     */
    public function setDistrict(array $district = [])
    {
        $this->offsetSet(self::KEY_DISTRICT, $district);
        return $this;
    }

    /**
     * 删除 district 地址
     *
     * @return $this
     */
    public function unsetDistrict()
    {
        if ($this->offsetExists(self::KEY_DISTRICT)) {
            $this->offsetUnset(self::KEY_DISTRICT);
        }
        return $this;
    }

    /**
     * 获取 district province 地址
     *
     * @return id | null
     */
    public function getDistrictProvince()
    {
        return count($this->getDistrict()) ? ($this->getDistrict())['province'] : null;
    }

    public function save()
    {
        if ($this->count()) {
            // 保存数据到 session
            session()->put(self::SESSION_KEY_LOCATION, $this->getArrayCopy());
        } else {
            // 删除数据到 session
            session()->forget(self::SESSION_KEY_LOCATION);
        }
    }

    /**
     * 析构函数，同步数据到 session
     */
    public function __destruct()
    {
        $this->save();
    }
}